//
//  AppDelegate+JPush.m
//  WeClubs
//
//  Created by KevinWang on 17/6/14.
//  Copyright © 2017年 Zed. All rights reserved.
//

#import "AppDelegate+JPush.h"
#import "ThirdPartKeyDefine.h"
#import "ZTabbarController.h"
#import "ZNavigationController.h"
#import "ZTodoMissionDetailVC.h"

#import "JPUSHService.h"
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif

@interface AppDelegate ()<JPUSHRegisterDelegate>

@end

@implementation AppDelegate (JPush)

- (void)JPushConfigWithLanchOption:(NSDictionary *)launchOptions{
    //init apns
    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
    entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        // 可以添加自定义categories
        // NSSet<UNNotificationCategory *> *categories for iOS10 or later
        // NSSet<UIUserNotificationCategory *> *categories for iOS8 and iOS9
    }
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    
    // init Push
    [JPUSHService setupWithOption:launchOptions appKey:JPushAppKey
                          channel:kAPPSource
                 apsForProduction:0
            advertisingIdentifier:nil];
    
    //
    if (launchOptions) {
        NSDictionary * remoteNotification = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
        //这个判断是在程序没有运行的情况下收到通知，点击通知跳转页面
        if (remoteNotification) {
            NSLog(@"推送消息==== %@",remoteNotification);
            [self goToMssageViewControllerWith:remoteNotification];
        }
    }
}

- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings{
    [application registerForRemoteNotifications];
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(nonnull NSData *)deviceToken{
    // JPush 注册deviceToken
    [JPUSHService registerDeviceToken:deviceToken];
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(nonnull NSError *)error{
    ZLog(@"apns注册失败");
}


- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{
    // 取得自定义字段内容，userInfo就是后台返回的JSON数据，是一个字典
    [JPUSHService handleRemoteNotification:userInfo];
    application.applicationIconBadgeNumber = 0;
    [self goToMssageViewControllerWith:userInfo];
}


#pragma mark- JPUSHRegisterDelegate

// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    // Required
    NSDictionary * userInfo = notification.request.content.userInfo;
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    completionHandler(UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以选择设置
}

// iOS 10 Support  one
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    // Required
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    [self goToMssageViewControllerWith:userInfo];
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    completionHandler();  // 系统要求执行这个方法
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
    // Required, iOS 7 Support
    [JPUSHService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}


- (void)applicationDidEnterBackground:(UIApplication *)application{
    //清除角标
    [application setApplicationIconBadgeNumber:0];
    [application cancelAllLocalNotifications];
}


#pragma mark - SEL

- (void)goToMssageViewControllerWith:(NSDictionary*)msgDic{
    
    UIViewController *vc = nil;
    int scene_id = [msgDic[@"scene_id"] intValue];
    switch (scene_id) {
        case 101:
        {
            NSString *dynamic_type = msgDic[@"dynamic_type"];
            if ([dynamic_type isEqualToString:@"mission"]) {
                
            }else if ([dynamic_type isEqualToString:@"notify"]){
            
            }else{
            
            }
        
        }
            break;
        case 102:
            
            break;
        case 103:
            
            break;
        case 201:
        {
            NSString *dynamic_type = msgDic[@"dynamic_type"];
            if ([dynamic_type isEqualToString:@"mission"]) {
                vc = [[ZTodoMissionDetailVC alloc] init];
            }else if ([dynamic_type isEqualToString:@"notify"]){
                
            }else{
                
            }
        }
            break;
        default:
            break;
    }
    [self PushToViewControllerWithVC:vc];
}

//根据类名来跳转对应界面
-(void)pushToViewControllerWithClassName:(NSString *)className {
    if (className != nil) {
        id myObj = [[NSClassFromString(className) alloc] init];
        @try {
            UITabBarController *tab = (UITabBarController *)self.window.rootViewController;
            UINavigationController  *nvc = tab.selectedViewController;
            UIViewController *vc = nvc.visibleViewController;
            vc.hidesBottomBarWhenPushed = YES;
            [vc.navigationController pushViewController:myObj animated:YES];
            vc.hidesBottomBarWhenPushed = NO;
        }
        @catch (NSException *exception) {
            // 捕获到的异常exception
        }
        @finally {
            // 结果处理
        }
    }
}

-(void)PushToViewControllerWithVC:(UIViewController *)vc {
    ZTabbarController *tab = (ZTabbarController *)self.window.rootViewController;
    ZNavigationController  *nvc = tab.selectedViewController;
    UIViewController *viewController = nvc.visibleViewController;
    viewController.hidesBottomBarWhenPushed=YES;
    [viewController.navigationController pushViewController:vc animated:YES];
    viewController.hidesBottomBarWhenPushed=NO;
}


@end
